package com.hkbigdata.watermark;

import com.hkbigdata.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;

/**
 * @author liuanbo
 * @creat 2024-05-09-14:01
 * @see 2194550857@qq.com
 */
public class Flink03_WaterMark_LateAndSideOutPut {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> waterSensorSingleOutputStreamOperator = env.socketTextStream("hadoop102", 9999)
                .flatMap(new FlatMapFunction<String, WaterSensor>() {
                    @Override
                    public void flatMap(String value, Collector<WaterSensor> out) throws Exception {
                        String[] split = value.split(",");
                        WaterSensor waterSensor = new WaterSensor(
                                split[0],
                                Long.valueOf(split[1]),
                                Integer.valueOf(split[2])
                        );
                        out.collect(waterSensor);
                    }
                });
        //有乱序数据，乱序程度3s,延迟3秒关窗
        WatermarkStrategy<WaterSensor> waterSensorWatermarkStrategy = WatermarkStrategy.<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3)).withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
            @Override
            public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                //提起事件时间来生成watermark
                return element.getTs() * 1000L;
            }
        });


        WindowedStream<WaterSensor, String, TimeWindow> result = waterSensorSingleOutputStreamOperator.assignTimestampsAndWatermarks(waterSensorWatermarkStrategy)
                .keyBy(WaterSensor::getId)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .allowedLateness(Time.seconds(2))
                .sideOutputLateData(new OutputTag<WaterSensor>("side") {
                });

        SingleOutputStreamOperator<WaterSensor> sum = result.sum("vc");

        sum.print("主流");
        sum.getSideOutput(new OutputTag<WaterSensor>("side") {
        }).keyBy(WaterSensor::getId).
                process(new KeyedProcessFunction<String, WaterSensor, WaterSensor>() {
                    private ValueState<WaterSensor> waterSensorValueState;

                    @Override
                    public RuntimeContext getRuntimeContext() {
                        return super.getRuntimeContext();
                    }

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        waterSensorValueState = this.getRuntimeContext().getState(new ValueStateDescriptor<WaterSensor>("state", WaterSensor.class));

                    }

                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<WaterSensor> out) throws Exception {
                        Integer lastvc = waterSensorValueState.value() == null ? 0 : waterSensorValueState.value().getVc();

                        WaterSensor waterSensor = new WaterSensor();
                        waterSensor.setId(value.getId());
                        waterSensor.setTs(value.getTs());
                        waterSensor.setVc(lastvc + value.getVc());
                        out.collect(waterSensor);

                        waterSensorValueState.update(waterSensor);
                    }
                }).print("侧输出流");


        env.execute();

    }
}
